package com.framework;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.framework.bean.Data;
import com.framework.bean.Handler;
import com.framework.bean.Param;
import com.framework.bean.View;
import com.framework.helper.BeanHelper;
import com.framework.helper.ConfigHelper;
import com.framework.helper.ControllerHelper;
import com.framework.util.ArrayUtil;
import com.framework.util.CodecUtil;
import com.framework.util.JsonUtil;
import com.framework.util.ReflectionUtil;
import com.framework.util.StreamUtil;
import com.framework.util.StringUtil;


/**
 * 请求转发器
 * @author ckm
 * 拦截了所有的 servlet 请求，获取请求的URL和数据，我们进行操作获取，返回执行结果。
 */
@WebServlet(urlPatterns="/*", loadOnStartup=0)
public class DispatcherServlet extends HttpServlet {

	private static final Object Data = null;

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		// 初始化相关 Helper 类
		HelperLoader.init();
		// 获取 ServletContext 对象(用于注册 Servlet)
		ServletContext servletContext = servletConfig.getServletContext();
		registerServlet(servletContext);
	}

	/**
	 * 注册 Servlet
	 * @param servletContext
	 * 理解还是有些欠缺
	 */
	private void registerServlet(ServletContext servletContext) {
		ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
		jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
		ServletRegistration defaultServlet = servletContext.getServletRegistration("default");	
		defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
	}
	
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
        	// 获取请求方法和路径
            String requestMethod = request.getMethod();
            String requestPath = request.getPathInfo();
            // 获取 Action 处理器
            Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
            if (handler != null) {
            	// 获取 Controller 类及其 Bean 实例
                Class<?> controllerClass = handler.getControllerClass();
                Object controllerBean = BeanHelper.getBean(controllerClass);
                // 创建请求参数对象
                HashMap<String, Object> paramMap = new HashMap<String, Object>();
                Enumeration<String> paramNames = request.getParameterNames();
                while(paramNames.hasMoreElements()) {
                	String paramName = paramNames.nextElement();
                	String paramValue = request.getParameter(paramName);
                	paramMap.put(paramName, paramValue);
                }
                String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
                if (StringUtil.isNotEmpty(body)) {
					String[] params = StringUtil.splitString(body, "&");
					if (ArrayUtil.isNotEmpty(params)) {
						for (String param : params) {
							String[] array = StringUtil.splitString(param, "=");
							if (ArrayUtil.isNotEmpty(array) && array.length==2) {
								String paramName = array[0];
								String paramvalue = array[1];
								paramMap.put(paramName, paramvalue);
							}
						}
					}
				}
                Param param = new Param(paramMap);
                // 调用 Action 方法
                Method actionMethod = handler.getActionMethod();
                Object result = null;
                // 判断参数是否为空, 调用不同的方法，后面还要修改和方法进行匹配
                if (param.isEmpty()) {
                	result = ReflectionUtil.invokeMethod(controllerBean, actionMethod);
				} else {
					result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
				}
                // 处理 Action 方法返回值
                if (result instanceof View) {
					// 返回 JSP 界面 JSP都不怎么用了，后面再说
                	View view = (View) result;
                	String path = view.getPath();
                	if (StringUtil.isNotEmpty(path)) {
					}
				} else if (result instanceof Data) {
					// 返回 JSON 数据
					Data data = (Data) result;
					Object model = data.getModel();
					if (model != null) {
						response.setContentType("application/json");
						response.setCharacterEncoding("UTF-8");
						PrintWriter writer = response.getWriter();
						String json = JsonUtil.toJson(model);
						writer.write(json);
						writer.flush();
						writer.close();
					}
				}
            }
        } finally {
        }

	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
